package com.learn.netty.groupchat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http2.InboundHttpToHttp2Adapter;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

/**
 *
 * netty群组聊天 服务器
 *
 * @author zhongshitao
 * @date 2020/10/23 5:30 下午
 */
@Slf4j
public class GroupChatServer {

    private static final int port = 8999;

    public GroupChatServer() {
    }


    public void run() {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap bootStrap = new ServerBootstrap();

            bootStrap.group(bossGroup, workerGroup)
                    .option(ChannelOption.SO_BACKLOG,128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer() {
                        /**
                         *
                         * @param ch
                         * @throws Exception
                         */
                        @Override
                        protected void initChannel(Channel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast("decode", new StringDecoder());
                            pipeline.addLast("encode", new StringEncoder());
                            pipeline.addLast(new GroupChatServerHandler());
                        }
                    });
            log.info("服务器已启动...");
            ChannelFuture channelFuture = bootStrap.bind(port).sync();

            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }


    public static void main(String[] args) {
        try {
            GroupChatServer groupChatServer = new GroupChatServer();

            groupChatServer.run();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }



}
